import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:lenovo
 * Date:2024-06-08
 * Time:16:15
 */
public class Test {
        private String filePath;

        public Test(String filePath) {
            this.filePath = filePath;
        }

        public void analyzeAndOutput(String outputType) {
            try {
                // 读取文本文件
                BufferedReader reader = new BufferedReader(new FileReader(filePath));
                String line;
                StringBuilder text = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    text.append(line).append("\n");
                }
                reader.close();

                // 统计字符和字符串数量
                int characterCount = text.length();
                int wordCount = text.toString().split("\\s+").length;

                // 输出结果
                if (outputType.equals("file")) {
                    FileWriter writer = new FileWriter("result.txt");
                    writer.write("Character count: " + characterCount + "\n");
                    writer.write("Word count: " + wordCount + "\n");
                    writer.close();
                    System.out.println("结果已保存至result.txt文件。");
                } else {
                    System.out.println("Character count: " + characterCount);
                    System.out.println("Word count: " + wordCount);
                }
            } catch (IOException e) {
                System.out.println("读取文件时出错：" + e.getMessage());
            }
        }

        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("请输入要统计的文本文件路径：");
            String filePath = scanner.nextLine();
            Test analyzer = new Test(filePath);

            System.out.print("请选择输出类型（file-文件，screen-屏幕）：");
            String outputType = scanner.nextLine();

            analyzer.analyzeAndOutput(outputType);
            scanner.close();
        }
    }
